<?php
/**
 * PHP 中的许多预定义变量都是“超全局的”，这意味着它们在一个脚本的全部作用域中都可用。
 * 在函数或方法中无需执行 global $variable; 就可以访问它们。
 *  $GLOBALS
    $_SERVER
    $_REQUEST
    $_POST
    $_GET

    $_FILES
    $_ENV
    $_COOKIE
    $_SESSION
 */

header("Content-type: text/html; charset=utf-8");

// $GLOBALS — 引用全局作用域中可用的全部变量
$x = 75;
$y = 25;

function addition() {
    $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

addition();
echo $z;
echo "<br>";

// $_SERVER 这种超全局变量保存关于报头、路径和脚本位置的信息。
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['GATEWAY_INTERFACE'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
echo "<br>";
echo $_SERVER['SERVER_SOFTWARE'];
echo "<br>";
echo $_SERVER['SERVER_PORT'];
echo "<br>";

// $_REQUEST 用于收集 HTML 表单提交的数据
if(!empty($_REQUEST['fname'])){
    echo "REQUEST", $_REQUEST['fname'];
    echo "<br>";
}


// $_POST 广泛用于收集提交 method="post" 的 HTML 表单后的表单数据。$_POST 也常用于传递变量
if(!empty($_POST['fname'])){
    echo "POST", $_POST['fname'];
    echo "<br>";
}


// $_GET 也可用于收集提交 HTML 表单 (method="get") 之后的表单数据。
if(!empty($_GET['fname'])){
    echo "subject:" . $_GET['subject'] . " web:" . $_GET['web'];
    echo "<br>";
}



// 定义变量并设置为空值
function test_input($data) {
    if(empty($data)){
        return "";
    }
    $data = trim($data);
    $data = stripslashes($data);
    // htmlspecialchars 安全
    $data = htmlspecialchars($data);
    return $data;
}

$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = test_input($_POST["name"]);
    $email = test_input($_POST["email"]);
    $website = test_input($_POST["website"]);
    $comment = test_input($_POST["comment"]);
    $gender = test_input($_POST["gender"]);

    echo $name, "<br>";
    echo $email, "<br>";
    echo $website, "<br>";
    echo $comment, "<br>";
    echo $gender, "<br>";
}

// preg_match 正则匹配
$match = preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email);
echo '检查电邮地址语法是否有效 ', $match;


?>
